import { OneModal } from '@/components/one-ui';
import React, { Ref, useCallback, useRef, useState } from 'react';
import { IOneModalRef } from '@/pages/type';
import { getKeyRouter, getLoadMapList, getTenantID, onCloseModalCommon } from '@/utils';
import { Button, Col, Form, Input, InputNumber, Row, Spin, Switch, DatePicker, TreeSelect, message, Select } from 'antd';
import { MaterialService } from '../services/MaterialService';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import pageStyles from '@/common/pageLayout.less';
import { RegularExpression } from '@/common/constVariable';
import { ILoadMapTypeAll } from '@/common';
import moment from 'moment';
const TimePicker: any = DatePicker;
/**
 * 选择物料弹框中的添加物料弹窗
 * */
export const UpdateAddEngIneerModal = ({ onClose, onSave }) => {
  /** 样式 */
  const prefixCls = 'need-update-';

  /** 弹窗ref */
  const addMaterialRef: Ref<IOneModalRef> = useRef(null);

  /** 添加物料表单的ref */
  const [addEngIneerForm] = Form.useForm();

  /** 字典获取 */
  const loadMdicIds: string[] = [`${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}`, `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`];
  const { loadMapInfo: loadMdicMapList, mapLoading } = getLoadMapList(loadMdicIds);

  /** 保存一份supplyTypeName 标的类型 */
  const [STdata, set_STdata] = useState<Record<string, any>>({});

  /**回调函数*/
  const addMaterialCallback = (res: Record<string, any>) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
      onCloseModalCommon(addMaterialRef);
    } else {
      message?.error('物料添加失败，请检查信息！');
    }
  };

  /**保存上级岗位搜索输入框的值*/
  const [treeSearch, setTreeSearch] = useState<string>('');

  // 处理树数据
  const orgTreeData = (data: any[]): any[] => {
    return data?.map((item: any) => {
      const name = item?.name;
      const nameLength = name?.length;
      const select = name?.search(treeSearch);
      const searchLength = treeSearch?.length;
      const afterStr = name?.slice(0, select);
      const selectStr = treeSearch;
      const beforeStr = name?.slice(select + searchLength, nameLength);
      const titleTree =
        select > -1 && selectStr ? (
          <span className={pageStyles['over-flow-hidden']}>
            {afterStr}
            <span style={{ color: '#f50' }}>{selectStr}</span>
            {beforeStr}
          </span>
        ) : (
          <span className={pageStyles['over-flow-hidden']}>{item?.name}</span>
        );

      if (item?.children && item?.children?.length > 0) {
        return {
          ...item,
          title: (
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                paddingRight: 20,
              }}
              id={item?.id}
            >
              {titleTree}
            </div>
          ),
          searchTitle: item?.name,
          key: item?.id,
          value: item?.id,
          children: orgTreeData(item?.children),
        };
      }
      return {
        ...item,
        title: (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              paddingRight: 20,
            }}
            id={item?.id}
          >
            {titleTree}
          </div>
        ),
        searchTitle: item?.name,
        key: item?.id,
        value: item?.id,
      };
    });
  };

  // 获取搜索框输入的值
  const treeSearchValue = useCallback(
    (valText: string) => {
      setTreeSearch(valText);
    },
    [treeSearch],
  );

  return (
    <OneModal
      open={true}
      getContainer={false}
      ref={addMaterialRef}
      title={'新增'}
      width={800}
      bodyStyle={{ padding: '15px' }}
      onCancel={onClose}
      footer={[
        <Button
          key="back"
          loading={false}
          onClick={() => {
            onCloseModalCommon(addMaterialRef);
          }}
        >
          取消
        </Button>,
        <Button
          key="submit"
          type="primary"
          loading={false}
          onClick={() => {
            addEngIneerForm?.validateFields()?.then((res: any) => {
              let addObj = {
                ...res,
                expectTime: res?.expectTime && moment(res?.expectTime)?.format('YYYY-MM-DD HH:mm:ss'),
                // supplyTypeName: STdata?.name,
                supplyType: `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}1001`,
                expectSum: (Number(res?.expectPrice) * Number(res?.expectNum)).toFixed(2),
                materialIDS: `${getKeyRouter()}${getKeyRouter()}${getKeyRouter()}`,
                singleFlag: Number(res?.singleFlag),
                importFlag: Number(res?.importFlag),
              };
              onSave(addObj);
              onCloseModalCommon(addMaterialRef);
            });
          }}
        >
          添加
        </Button>,
      ]}
    >
      <Spin spinning={false}>
        <ScrollBarLayout style={{ padding: '0.5rem 0' }}>
          <div className={Cls(pageStyles['fromView-styles'], prefixCls + 'addEngIneer')}>
            <Form form={addEngIneerForm}>
              <Row>
                <Col span={24}>
                  <Form.Item
                    label="标的名称"
                    name="fullName"
                    rules={[
                      {
                        required: true,
                        message: '请输入标的名称',
                      },
                    ]}
                  >
                    <Input placeholder="请输入" />
                  </Form.Item>
                </Col>

                {/* <Col span={12}>
                  <Form.Item
                    label="标的类别"
                    name="supplyType"
                    rules={[
                      {
                        required: true,
                        message: '请选择标的类别',
                      },
                    ]}
                  >
                    <Select
                      placeholder="请选择"
                      loading={mapLoading}
                      onSelect={(val, node) => {
                        set_STdata({
                          id: node?.value,
                          name: node?.children,
                        });
                      }}
                    >
                      {loadMdicMapList?.[`${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}`]?.map((item: any) => {
                        if (item?.id != `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}1000`) {
                          return (
                            <Select.Option key={item?.id} value={item?.id}>
                              {item?.name}
                            </Select.Option>
                          );
                        }
                      })}
                    </Select>
                  </Form.Item>
                </Col> */}

                <Col span={24}>
                  <Form.Item
                    label="规格要求(参数)"
                    name="needParams" // needParams[需求物料表中]  specInfo[物料表中]
                    rules={[
                      {
                        required: true,
                        message: '请输入规格要求(参数)',
                      },
                      // {
                      //   pattern: RegularExpression?.noChinese,
                      //   message: '规格要求(参数)只能填字母和数字！',
                      // },
                    ]}
                  >
                    <Input.TextArea placeholder="请输入" allowClear maxLength={200} autoSize={{ minRows: 3 }} />
                  </Form.Item>
                </Col>

                <Col span={12}>
                  <Form.Item
                    label="预估单价"
                    name="expectPrice"
                    // rules={[
                    //   {
                    //     required: true,
                    //     message: '请输入预估单价',
                    //   },
                    // ]}
                    initialValue={0.0}
                  >
                    <InputNumber precision={2} min={0} placeholder="请输入" addonAfter={'元'} />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label="需求数量"
                    name="expectNum"
                    rules={[
                      // {
                      //   required: true,
                      //   message: '请输入需求数量',
                      // },
                      {
                        pattern: RegularExpression?.number,
                        message: '需求数量必须为整数！',
                      },
                    ]}
                    initialValue={1}
                  >
                    <InputNumber min={0} placeholder="请输入" />
                  </Form.Item>
                </Col>

                <Col span={12}>
                  <Form.Item
                    label="量化单位"
                    name="unitBusiness"
                    rules={[
                      {
                        required: true,
                        message: '请选择量化单位',
                      },
                    ]}
                  >
                    <Select placeholder="请选择" loading={mapLoading}>
                      {loadMdicMapList?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`]?.map((item: any) => {
                        return (
                          <Select.Option key={item?.id} value={item?.id}>
                            {item?.name}
                          </Select.Option>
                        );
                      })}
                    </Select>
                  </Form.Item>
                </Col>

                <Col span={12}>
                  <Form.Item label="计划采购时间" name="expectTime" initialValue={null}>
                    <TimePicker
                      bordered={true}
                      picker="month"
                      defaultPickerValue={[moment().add(1, 'month').startOf('month'), moment().add(1, 'month').startOf('month').clone().endOf('month')]}
                      disabledDate={(current: any) => {
                        // 设置某一个时间（例如：2023年7月15日）当前月也可以选择
                        const afterDate = moment(new Date(), 'YYYY-MM-DD').add(0, 'month');
                        // 返回 true 表示禁用，false 表示可选
                        return current && current < afterDate;
                      }}
                    />
                  </Form.Item>
                </Col>

                <Col span={12}>
                  <Form.Item label="标包号" name="packCode">
                    <InputNumber placeholder="请输入" />
                  </Form.Item>
                </Col>

                <Col span={12}>
                  <Form.Item label="是否平台" name="isPlatform">
                    <TagSelect
                      colSpan={24}
                      formLabel={''}
                      formName={'isPlatform'}
                      radioList={[
                        {
                          value: 0,
                          name: '否',
                        },
                        {
                          value: 1,
                          name: '是',
                        },
                      ]}
                    />
                  </Form.Item>
                </Col>

                <Col span={12}>
                  <Form.Item label="是否进口" name="importFlag">
                    {/* <Switch
                      checkedChildren="是"
                      unCheckedChildren="否"
                    /> */}
                    <TagSelect
                      colSpan={24}
                      formLabel={''}
                      formName={'importFlag'}
                      radioList={[
                        {
                          value: 0,
                          name: '否',
                        },
                        {
                          value: 1,
                          name: '是',
                        },
                      ]}
                    />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item label="是否单一来源" name="singleFlag">
                    <TagSelect
                      colSpan={24}
                      formLabel={''}
                      formName={'singleFlag'}
                      radioList={[
                        {
                          value: 0,
                          name: '否',
                        },
                        {
                          value: 1,
                          name: '是',
                        },
                      ]}
                    />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </div>
        </ScrollBarLayout>
      </Spin>
    </OneModal>
  );
};
